package com.w.utils.thread.concurrent;
/**
 *
 **/

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author weiwei
 * @Date 2020-11-16 21:50
 * @description 自定义线程工厂
 **/
public class CustomerThreadFactory implements ThreadFactory {


    private final AtomicInteger mThreadNum = new AtomicInteger(1);

    private static final AtomicInteger POOL_SEQ = new AtomicInteger(1);

    private final String cPrefix;

    //是否是守护线程
    private final boolean cDaemon;

    private final ThreadGroup mGroup;

    public CustomerThreadFactory() {
        //getAndIncrement返回+1前的值
        this("pool-" + POOL_SEQ.getAndIncrement(), false);
    }

    public CustomerThreadFactory(String prefix) {
        this(prefix, false);
    }

    public CustomerThreadFactory(String prefix, boolean daemon) {
        cPrefix = prefix + "-thread-";
        cDaemon = daemon;
        SecurityManager s = System.getSecurityManager();
        mGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
    }

    @Override
    public Thread newThread(Runnable runnable) {
        String name = cPrefix + mThreadNum.getAndIncrement();
        Thread ret = new Thread(mGroup, runnable, name, 0);
        ret.setDaemon(cDaemon);
        return ret;
    }

    public ThreadGroup getThreadGroup() {
        return mGroup;
    }
}
